package com.davesandoval.tpdroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

public class SODetailsActivity extends Activity {
	private static Cursor dCursor;
	private Cursor nCursor;
	private String message;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sodetails);
		Bundle extras = getIntent().getExtras();
		int position = extras.getInt("position");
		
		if (Main.dbHelper.isOpen()){
			dCursor = Main.dbHelper.fetchAllSO();
			startManagingCursor(dCursor);
			dCursor.moveToPosition(position);
			nCursor = Main.dbHelper.fetchAccountViaNumber(dCursor.getString(dCursor
					.getColumnIndex(TPdbAdapter.KEY_ACCOUNT_NUMBER)));
			startManagingCursor(nCursor);
			
		} else {
			Main.dbHelper.open();
			dCursor = Main.dbHelper.fetchAllSO();
			startManagingCursor(dCursor);
			dCursor.moveToPosition(position);
			nCursor = Main.dbHelper.fetchAccountViaNumber(dCursor.getString(dCursor
					.getColumnIndex(TPdbAdapter.KEY_ACCOUNT_NUMBER)));
			startManagingCursor(nCursor);
		}
		

		final int resultCode = 0;
		final TextView tvSONumber = (TextView) findViewById(R.id.tvSONum);
		TextView tvAccountName = (TextView) findViewById(R.id.tvAccountName);
		final TextView tvAccountAddress = (TextView) findViewById(R.id.tvAccountAddress);
		TextView tvContactName = (TextView) findViewById(R.id.tvContactName);
		final TextView tvContactNumber = (TextView) findViewById(R.id.tvContactNumber);
		TextView tvSODescription = (TextView) findViewById(R.id.tvSODetail);
		TextView tvWorkPerformed = (TextView) findViewById(R.id.tvWorkPerformed);
		message = getMessage();
		
		tvSONumber.setText(dCursor.getString(dCursor
				.getColumnIndex(TPdbAdapter.KEY_SO_NUM)));
		tvAccountName.setText(dCursor.getString(dCursor
				.getColumnIndex(TPdbAdapter.KEY_ACCOUNT_NAME)));
		tvAccountAddress.setText(nCursor.getString(nCursor
				.getColumnIndex(TPdbAdapter.KEY_ADDRESS)));
		tvContactName.setText(nCursor.getString(nCursor
				.getColumnIndex(TPdbAdapter.KEY_CONTACT_NAME)));
		tvContactNumber.setText(nCursor.getString(nCursor
				.getColumnIndex(TPdbAdapter.KEY_CONTACT_PHONE)));
		tvSODescription.setText(dCursor.getString(dCursor
				.getColumnIndex(TPdbAdapter.KEY_DESCRIPTION)));
		tvSODescription.setMovementMethod(new ScrollingMovementMethod());
		
		registerForContextMenu(tvAccountAddress);
		
		Button btnViewWorkPerformed = (Button) findViewById(R.id.btnViewWorkPerformed);
		Button btnAddLog = (Button) findViewById(R.id.btnAddLog);
		Button btnViewPrintableSO = (Button) findViewById(R.id.btnViewPrintableSO);

		btnAddLog.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(SODetailsActivity.this, AddSOLog.class);
				intent.putExtra("soNum", tvSONumber.getText().toString());
				startActivityForResult(intent, resultCode);
			}
		});
		
		btnViewPrintableSO.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (isOnline()){
					Intent intent = new Intent(SODetailsActivity.this, ViewPrintableSO.class);
					intent.putExtra("soNum", tvSONumber.getText().toString());
					startActivityForResult(intent, resultCode);
				} else {
					Toast.makeText(
							getBaseContext(),
							"You have no Internet connection currently,\n"
									+ "please try again after the network comes online.",
							Toast.LENGTH_LONG).show();
				}
			}
		});

		btnViewWorkPerformed.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//String message = getMessage();
						AlertDialog.Builder builder = new AlertDialog.Builder(SODetailsActivity.this);
						builder.setCancelable(true);
						builder.setTitle("Work Performed");
						builder.setMessage(message);
						builder.setInverseBackgroundForced(true);
						builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
						//@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});

		tvAccountAddress.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String address = tvAccountAddress.getText().toString();
				// This Intent will map the address using browser or google maps
				// String address = "5268 Azo ct kalamazoo mi 49048";
				Intent searchAddress = new Intent(Intent.ACTION_VIEW, Uri
						.parse("http://maps.google.com/maps?q=" + address));

				// The following Intent is for automatic navigation based on
				// current location
				/*
				 * Intent searchAddress = new
				 * Intent(Intent.ACTION_VIEW,Uri.parse(
				 * "google.navigation:q="+address));
				 */
				startActivity(searchAddress);
			}
		});

		tvContactNumber.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String phNum = tvContactNumber.getText().toString();
				phNum = phNum.replace("(", "").replace(")", "").replaceAll(" ", "").replaceAll("-", "");
				Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phNum));
				startActivity(i);
			}
		});
		

	}// ----END ONCREATE---------------

 	protected static String getMessage() {
		String result = dCursor.getString(dCursor.getColumnIndex(
				TPdbAdapter.KEY_WORK_PERFORMED)).toString();
		if (result.length() < 1) {
			return "The server says there are no logs yet...";
		} else {
			return result;
		}
	}

	@Override
	protected void onPause() {
		System.out.println("------SODetailsActivity onPause------");
		stopManagingCursor(dCursor);
		stopManagingCursor(nCursor);
		super.onPause();
	}

	@Override
	protected void onStop() {
		System.out.println("------SODetailsActivity onStop------");
		stopManagingCursor(dCursor);
		stopManagingCursor(nCursor);
		super.onStop();
	}
	
	@Override
	public void onResume(){
		System.out.println("------SODetailsActivity onResume------");
		Main.dbHelper.open();
		startManagingCursor(dCursor);
		startManagingCursor(nCursor);
		super.onResume();
	}

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnected()) {
			return true;
		}
		return false;
	}
}